<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入订单名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="合同id" prop="contractId">
        <el-input v-model="queryParams.contractId" placeholder="请输入合同id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
          <el-option v-for="dict in store_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户id" prop="cId">
        <el-input v-model="queryParams.cId" placeholder="请输入用户id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="Id" align="center" prop="id" />
      <el-table-column label="订单名称" align="center" prop="name" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="合同id" align="center" prop="contractId" />
      <el-table-column label="审批状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="store_type" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="用户id" align="center" prop="cId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['warehouseout:warehouseout:edit']" :disabled="scope.row.status !== '0'">审批通过</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['warehouseout:warehouseout:remove']" :disabled="scope.row.status !== '0'">审批驳回</el-button>
          <el-button link type="primary" icon="ZoomIn" @click="openOrder(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 显示出库详情 -->
    <el-dialog title="出库订单信息" v-model="openOder" width="500px" append-to-body>
      <div class="demo-collapse">
        <el-collapse :data="formData" :key="id" accordion>
          <el-collapse-item :title="`订单号:${formData.orderNo}`">
            <div>
              <p>订单名称: {{ formData.name }}</p>
              <p>发货状态：{{ formData.status === '3' ? '已完成' : '未完成' }}</p>
              <p>合同类型: {{ formData.type === "1" ? '租用' : '服务' }}</p>
              <p>合同签订时间: {{ formData.serviceTime }}</p>
              <p>合同到期时间: {{ formData.expirationTime }}</p>
              <p>合同金额: {{ formData.money }}</p>
            </div>
            <el-table :data="formData.orderNumber" style="width: 100%">
              <el-table-column prop="goodsId" label="商品ID" width="270" />
              <el-table-column prop="number" label="数量" width="180" />
            </el-table>
            <el-button size="small" type="primary" round @click="complet(formData.orderNumber)" v-show="statusOne === '1'">确认入库</el-button>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-dialog>

    <!-- 确认收货 -->
    <el-dialog title="确认入库" v-model="completedDialog" width="500px" append-to-body>
      <div class="demo-collapse" v-for="form in goodLoactionList">
        <el-collapse :data="form" :key="id" accordion>
          <el-collapse-item :title="`商品号:${form.goodsId}`">
            <el-form :inline="true" :model="form" class="demo-form-inline" :loading="lodaingArea">
              <div class="m-4">
                <p>选择存放库区货位</p>
                <el-cascader v-model="form.area" :options="warehouseOptions" :props="propData" @change="handleChange" placeholder="请选择货位"/>
              </div>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
      <el-form-item>
                <el-button type="primary" @click="onSubmit()">确认</el-button>
              </el-form-item>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listStore, getStore, updateOrder } from "@/api/customer/store"
import { delGoods, listGoods } from "@/api/customer/goods";
import { reactive } from "vue";
import {listWarehouse,getWarehouseAllFor} from "@/api/warehouseManagement/warehouse"
import { addGoodsStore } from "@/api/goodsStore/goodsStore"
import { Inset } from "@/api/warehouseout/inventory"
import { updateLocation } from "@/api/location/location"

const { proxy } = getCurrentInstance();
const { store_type } = proxy.useDict('store_type');
const propData =ref({ label:"name",value:"id",children:"children" })

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
let openOder = ref(false)
let formData = ref()
let completedDialog = ref(false)
let completData = ref()
let areaData = ref()
// tree
const warehouseOptions = ref([])
let lodaingArea = ref(true)



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    orderNo: null,
    contractId: null,
    status: null,
    cId: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

//提交货物入库
function onSubmit() {
    goodLoactionList.value.forEach(form=>{
    form.orderId=id.value
    form.warehouseId=form.area[0]
    form.areaId=form.area[1]
    form.shelfId=form.area[2]
    form.locationId=form.area[3]
    return addGoodsStore(form)
    })
  console.log(goodLoactionList.value);
  completedDialog.value = false
    const data = {
       id : id.value,
      status : 3
    }
    updateOrder(data)
    Inset(formData.value.orderNumber)
    let data2 = reactive({  
      id: 0,  
      status: 1  
    });
    goodLoactionList.value.forEach(form=>{
      data2.id = form.locationId,
      data2.status = 1
    return updateLocation(data2)
    })
    getList(),
    proxy.$modal.msgSuccess("操作成功")
    
}

//获取仓库列表
function getAreaList(){
  return getWarehouseAllFor().then((res)=>{
    console.log(res);
    let data = res.data.map(warehouse => {
        // 设置仓库
        const warehouseNode = {
            ...warehouse,
            nodeId: 2,
            children: warehouse.areas.map(area => {
                // 设置库区
                const areaNode = {
                    ...area,
                    nodeId: 3,
                    children: area.shels.map(shelf => {
                        // 设置货架
                        return {
                            ...shelf,
                            nodeId: 4,
                            children:shelf.locations.map(location =>{
                              return {
                                ...location,
                                name:location.locationNo
                              }
                            })
                        };
                    })
                };
                return areaNode;
            })
        };
        return warehouseNode;
    });
    warehouseOptions.value = data
    lodaingArea.value = false
  })
}

getAreaList()

//确认入库
function complet(Data) {
  completData.value = Data
  goodLoactionList.value.forEach(element => {
    goodLoactionList.orderId = 0;
    goodLoactionList.warehouseId = '';
    goodLoactionList.areaId = 0;
    goodLoactionList.shelfId = 0;
    goodLoactionList.locationId = 0,
    goodLoactionList.area = []
  });
  openOder.value = false
  completedDialog.value = true
}

let statusOne = ref()
let goodLoactionList = ref([])

/**显示详细信息 */
function openOrder(row) {
  goodLoactionList.value=([])
  id.value = row.id
  statusOne.value = row.status
  return getStore(row.id).then((res) => {
    formData.value = res.data
    formData.value.orderNumber.map(item=>{
      for (let index = 0; index < item.number; index++) {
      goodLoactionList.value.push(
        {
          goodsId:item.goodsId
        }
      )
    }
    })
    console.log(formData.value.orderNumber);
    openOder.value = true
  })
}

/** 查询商品订单列表 */
function getList() {
  listStore(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
  })
  loading.value = false
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    orderNo: null,
    contractId: null,
    status: null,
    cId: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品订单";
}

let id = ref()

/** 通过审批按钮操作 */
function handleUpdate(row) {
  proxy.$modal.confirm('是否确认通过订单编号为"' + row.orderNo + '"的数据项？').then(function () {
    const data = {
      id: row.id,
      status: 1
    }
    return updateOrder(data).then(() => {
      getList();
      proxy.$modal.msgSuccess("通过成功");
    }).catch(() => { });
  })
}


/** 审批驳回按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认驳回订单编号为"' + row.orderNo + '"的数据项？').then(function () {
    const data = {
      id: row.id,
      status: 2
    }
    return updateOrder(data);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("驳回成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('warehouseIn/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

getList();
</script>
